<template>
  <div class="profile">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <h2>个人中心</h2>
        </div>
      </template>

      <el-form 
        v-if="userInfo" 
        :model="userInfo" 
        label-width="120px"
        class="profile-form"
      >
        <el-form-item label="用户名">
          <el-input v-model="userInfo.username" disabled />
        </el-form-item>

        <el-form-item label="邮箱">
          <el-input v-model="userInfo.email" />
        </el-form-item>

        <el-form-item label="注册时间">
          <el-input v-model="userInfo.created_at" disabled />
        </el-form-item>

        <el-form-item label="生成总数">
          <el-input v-model="userInfo.total_generated" disabled />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleUpdate">保存修改</el-button>
        </el-form-item>
      </el-form>

      <div v-else-if="loading" class="loading">
        <el-skeleton :rows="4" animated />
      </div>

      <div v-else class="error-message">
        <el-empty description="获取用户信息失败" />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import request from '../utils/request'

const userInfo = ref(null)
const loading = ref(false)

const getUserProfile = async () => {
  try {
    loading.value = true
    const response = await request.get('user/profile')
    
    if (response.status === 'success') {
      userInfo.value = response.data
    } else {
      ElMessage.error('获取用户信息失败')
    }
  } catch (error) {
    console.error('Error getting user profile:', error)
    ElMessage.error('获取用户信息失败：' + error.message)
  } finally {
    loading.value = false
  }
}

const handleUpdate = async () => {
  try {
    const response = await request.put('user/profile', {
      email: userInfo.value.email
    })
    
    if (response.data.status === 'success') {
      ElMessage.success('更新成功')
      await getUserProfile()  // 重新获取用户信息
    } else {
      ElMessage.error('更新失败')
    }
  } catch (error) {
    console.error('Error updating profile:', error)
    ElMessage.error('更新失败：' + error.message)
  }
}

onMounted(() => {
  getUserProfile()
})
</script>

<style scoped>
.profile {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
}

.profile-card {
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.card-header {
  text-align: center;
}

.card-header h2 {
  margin: 0;
  color: var(--primary-color);
}

.profile-form {
  margin-top: 20px;
}

.loading {
  padding: 20px;
}

.error-message {
  text-align: center;
  padding: 20px;
}
</style> 